package com.banshuibao.bsb_android.util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by wangpan on 2017/12/20.
 */

public class PareUtils {

    public static HashMap parserToMap(String s) throws JSONException {
        HashMap map = new HashMap();
        JSONObject json = new JSONObject(s);
        Iterator keys = json.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = json.get(key).toString();
            if (value.startsWith("{") && value.endsWith("}")) {
                map.put(key, parserToMap(value));
            } else {
                map.put(key, value);
            }

        }
        return map;
    }

    /**
     * 将hashMap转为json
     */
    public static String hashMapToJson(HashMap map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry e = (Map.Entry) it.next();
            string += "'" + e.getKey() + "':";
            string += "'" + e.getValue() + "',";
        }
        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }
}
